package study.async.springboot.support.utils;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import study.eggs.result.Result;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Slf4j
public final class WebUtils {

    private WebUtils() {
    }

    public static void write(HttpServletResponse response, int statusCode) {
        response.setStatus(statusCode);
    }

    public static void write(ServletResponse response, Result result) {
        PrintWriter writer = null;
        try {
            response.setContentType("application/json; charset=UTF-8");
            writer = response.getWriter();
            String text = JSONUtil.toJsonStr(result);
            writer.write(text);
        } catch (Exception ex) {
            log.error("", ex);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}
